package bsc.war.form;

import bsc.ejb.entity.Person;
import bsc.ejb.entity.PersonScoreDomain;
import bsc.ejb.entity.ScoreDomain;
import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 *
 * @author memozac
 */
public class NewPassword extends AbstractController {

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        try {
            DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");
            Long idPerson = request.getParameter("idPerson") != null ? Long.valueOf(request.getParameter("idPerson")) : null;

            Person person = delegate.findPerson(idPerson);
            person.setPassword(request.getParameter("newPassword"));
            delegate.updatePerson(person);

            request.getSession(true).setAttribute("person", person);

            //Change Default Domain
            //Change false the default domain
            List<ScoreDomain> trueScoreDomain = delegate.findScoreDomain(person, Boolean.TRUE);
            for (ScoreDomain scoreDomain : trueScoreDomain) {
                PersonScoreDomain personScoreDomain= delegate.findPersonScoreDomain(person, scoreDomain);
                personScoreDomain.setDefaultDomain(Boolean.FALSE);
                delegate.updatePersonScoreDomain(personScoreDomain);
            }

            //Change true the new default domain
            Long idSelectedScoreDomain = Long.parseLong(request.getParameter("idScoreDomain"));
            ScoreDomain scoreDomain = delegate.findScoreDomain(idSelectedScoreDomain);
            PersonScoreDomain personScoreDomain= delegate.findPersonScoreDomain(person, scoreDomain);
            personScoreDomain.setDefaultDomain(Boolean.TRUE);
            delegate.updatePersonScoreDomain(personScoreDomain);
            

        } catch (Exception e) {
            e.printStackTrace();
        }

        return new ModelAndView("newPassword");
    }
}
